package middleware

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"time"
	"{{cookiecutter.app_name}}/common/errorx"
)

type JwtExtMiddleware struct {
	Redis *redis.Redis
	APP   string
}

func NewJwtExtMiddleware(Redis *redis.Redis, app string) *JwtExtMiddleware {
	return &JwtExtMiddleware{Redis: Redis, APP: app}
}

func (m *JwtExtMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id := r.Context().Value("userId").(string)
		token := r.Context().Value("token").(string)
		logx.Infof("id=%v", id)

		//用户是否被block
		if true {
			key := fmt.Sprintf("%v:user:block:%v", m.APP, id)
			b, myerr := m.Redis.Exists(key)
			if b || myerr != nil {
				httpx.WriteJson(w, 401, errorx.NewCodeErrorNoMsg(401))
				return
			}
		}

		key := fmt.Sprintf("%v:user:token:%v", m.APP, id)
		curToken, err := m.Redis.GetCtx(r.Context(), key)
		logx.Infof("curToken=%v", curToken)
		if err != nil || curToken != token {
			logx.Errorf("用户ID=%v不存在", id)
			//httpx.Error(w, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR+8))
			httpx.WriteJson(w, 401, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR+8))
			return
		}
		//使用redis 的incrby 修改今天接口访问数
		today := time.Now().Format("2006-01-02")
		k := fmt.Sprintf("%v:stats:%v:q_count", m.APP, today)
		m.Redis.Incrby(k, 1)
		//统计今日用户访问数
		k1 := fmt.Sprintf("%v:stats:%v:activeuser", m.APP, today)
		m.Redis.Zadd(k1, 1, fmt.Sprintf("%v", id))
		next(w, r)
	}
}
